'use strict'

process.chdir(__dirname);//自动切换到自己所在目录里面

const fs = require('fs');
const titbit = require('titbit');
const pg = require('pg');
const dbconfig = require('./dbconfig.js');
const wxkey = require('./wxkey.js')
//使用HTTP/1.1的客户端
const {httpcli} = require('gohttp');
const token = require('titbit-token');
const tbloader = require('titbit-loader');
let tok = new token({
    //token有效期，单位是秒
    expires:30,

    //必须是32位字母数字
    key:'1wdsdyf2dr45tod84kfht83mfhdjrexd',

    //必须是16位字母数字
    iv:'12sd3fgru4idsjrf'
});

let psql = new pg.Pool(dbconfig);

try{
    fs.accessSync('./images')
    //如果文件中存在路径目录为images,直接进入
}catch(err){
    fs.mkdirSync('./images')
    //如果文件中不存在路径目录为images,创建mul
}

let cert_path = '/usr/local/share'
const app = new titbit({
    //开启调试模式，会输出错误信息
    debug:true,
    globalLog:true,
    cert:`${cert_path}/aaa.coralmh.xyz.pem`,
    key:`${cert_path}/aaa.coralmh.xyz.key`
})

let tb = new tbloader();
tb.init(app);

//在app.service对象上添加了一个属性
app.addService('tok',tok);
app.addService('psql',psql);
app.addService('imagePath',`${__dirname}/images`);

//c 就是 context
app.get('/',async c => {
    c.send('ok')
})
app.get('/upload',async c => {
    //c.helper是助手函数模块 其中有对stream.pipe函数的封装
    //c.reply是响应对象，http/1.1中指向response，http/2中指向stream
    await c.helper.pipe('./upload.html',c.reply);
});

//JS无需加分号，谁用谁知道，有时也得加分号，括号开头很需要
//箭头函数是用来解救this的    (async () => {})();

app.get('/user/:name/:age/:mobile',async c => {
    console.log(c.param)
    c.send(c.param)
})

app.get('/mp-login/:code',async c => {
    c.send(c.param);
    let auth_url = `https://api.weixin.qq.com/sns/jscode2session`+`?appid=${wxkey.appid}`+`&secret=${wxkey.secret}`
                    +`&js_code=${c.param.code}`+`&grant_type=authorization_code`;
    let ret = await httpcli.get(auth_url)
    .then(res => res.json())
    // .then(res => {
    //     return res.text()
    // })
    c.send(tok.make(ret))
})

//监听1234端口运行服务
app.run(2002);